// pages/order/payment/index.js
const api = require("../../../utils/api")
var app =getApp()
Page({
  data: {
    goods: '',
    radio:'1',  //改变收获地址选项
    name:'',
    phone:'',
    address:'',
    order_code:'13672467247',
    shopName:'小象精选',
    images:[],  //显示的图片
    jifen:0,  //剩余积分
    beizhu:'', //添加的备注信息
    checked:true,  //积分支付选中
    type:'success',  //积分支付选中样式
    activeNames:[], //备注面板
    price:0,  // 商品总计
    spyh:0,  // 商品优惠
    postage:2, // 邮费
    totalPrice:0,  // 总付款
    serverHost: app.config.serverHost
  },
  // 改变收获地址
  changeReceiver(){
    wx.navigateTo({
      url: '/pages/map/index'
    })
  },
  // 添加备注信息
  changeBaiZhu(e){
    this.setData({
      beizhu:e.detail.value
    })
  },
  // 改变收货方式
  onChange(e) {
    if(this.data.radio == e.detail) return
    this.setData({
      radio: e.detail
    })
    e.detail == '2' ? this.changePrice(-this.data.postage) : this.changePrice(this.data.postage)
  },
  // 支付按钮
  pay(){
    if(this.data.address == ''){
      wx.showToast({
        title: '请前去选择地址',
        icon: 'none',
        duration: 1500,
        mask: false
      })
      return
    }

//获取openid
var that =this;
    console.log(that.data.goods)
    var number = [...that.data.goods]
    console.log(number)
    app.api.post('web/upgoodlist', number, (res) => {
      console.log(res)
    })
var datas ={
  body: that.data.shopName,
  openid: wx.getStorageSync('openid'),
  paySigns: that.data.order_code,
  goods_list: that.data.goods,
  cash_fee: that.data.totalPrice,
  address:{
    name: that.data.name,
    phone: that.data.phone,
    local: that.data.address,
  }, 
  beizhu: that.data.beizhu,
  way: that.data.radio,
  token: wx.getStorageSync('token')
}

    app.api.getData('/pays', datas, (res) => {
      var shopping_cart = wx.getStorageSync('shopping_cart')
      var a = []
      that.data.goods.forEach(item=>{
        a.push(item.id)
      })
      app.globalData.goodslist.filter(e => {
        if (a.includes(e._id)) {
          e.value = 0
        }
      })
      let temp = shopping_cart.filter(e => {
        return !a.includes(e.goods)
      })
      wx.setStorageSync('shopping_cart', temp)
      const model = {
        token: wx.getStorageSync('token'),
        shopping_cart: wx.getStorageSync('shopping_cart')
      }
      app.api.updateData('web/goodscart', model, (res) => { })

wx.requestPayment({
  timeStamp: res.data.timeStamp,
  nonceStr: res.data.nonceStr,
  package: res.data.package,
  signType: res.data.signType,
  paySign: res.data.sign,

  'success': function (res) {
    console.log("success", res)
   
    wx.redirectTo({
      url: '/pages/my/order/index',
    })

  },
  'fail': function (res) { 
    console.log("fail", res) 
    wx.redirectTo({
      url: '/pages/my/order/index',
    })
  },
})

    })


  },
  formatDate(len) {
    len = len || 42;
    var chars = '1234567890';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;

},
  onLoad: function (e) {
    let _this = this
    let goods = JSON.parse(e.ids)
    let id = JSON.parse(e.id) //传递的id
    let value = []  //传递的数量
    let images = [] //临时存放数据图片
    let temp = [] //临时存放要显示的images的图片
    let youhui = 0  //商品优惠
    // 传递过来的id
    console.log(goods)
    console.log(JSON.parse(e.id))
    // 传递过来的数量
    JSON.parse(e.id).filter(item => {
      value.push(item.value)
    })
  
      // 获取数据的图片放入到images中、设置商品优惠youhui、商品数量value
      goods.filter((item,index) => {
        images.push(item.goods_imgUrl)
        value.filter((e,ind)=>{
          index == ind ? (youhui += (item.oprice - item.price) * e,item.value = e) : ''
        })
      })
      // 提取数据的首张图片放入到temp
      images.filter(item=>{
        temp.push(item[0])
      })

      var ordercode = _this.formatDate(20);
  
      _this.setData({
        goods: id,
        order_code: ordercode,
        price:parseFloat(e.price),
        totalPrice:parseFloat(e.price) + parseFloat(this.data.postage),
        images:temp,
        spyh:youhui
      })
      console.log(_this.data.order_code)
      // 调用改变价格函数，参数为积分转为的金额
      _this.changePrice(_this.data.jifen)
    
    let token = { token: wx.getStorageSync('token') }
    app.api.getData('admin/address',token,(res)=>{
      res.data.length == 0 ? _this.setData({name:'请前去选择收货地址'}) : _this.setData({name:res.data[0].name,phone:res.data[0].phone,address:res.data[0].local})
    })
  },
  // 是否使用积分支付
  toggle(){
    this.data.type == 'circle' ? (this.setData({type:'success'}),this.changePrice(this.data.jifen)) : (this.setData({type:'circle'}),this.changePrice(-this.data.jifen))
  },
  // 改变价格
  changePrice(e){
    let _this = this
    _this.setData({
      totalPrice:_this.data.totalPrice - e
    })
  }
})